package licode.unisop.client.utils;

import licode.unisop.client.api.auth.SopUserAuth;
import licode.unisop.client.feign.SopUserAuthFeign;
import licode.unisop.client.info.SopRegisterUserIn;
import licode.unisop.client.info.SopTokenInfo;
import licode.unisop.client.info.SopUpdatePasswordIn;
import licode.unisop.client.info.SopUserIdFind;
import licode.unisop.client.service.impl.SopAuthCheck;
import licode.unisop.client.vo.SopAuthPlatform;
import licode.unisop.client.vo.SopUserBrief;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 用户操作服务类
 *
 * @author licode
 */
@Component
public class SopUserQueryUtil {
    @Resource
    HttpServletRequest request;

    @Resource
    private SopUserAuth sopUserAuth;

    @Resource
    private SopAuthCheck sopAuthCheck;

    @Resource
    private SopUserAuthFeign sopUserAuthFeign;

    protected SopAuthPlatform checkPlatform() {
        SopAuthPlatform platform = sopAuthCheck.getPlatform(request);
        if (null == platform || !platform.isValid()) {
            // 平台不可用（在认证中心没有注册）
            SopException.throwBy(403, "无效平台！");
        }
        return platform;
    }

    public String updatePassword(SopUpdatePasswordIn info) {
        SopTokenInfo tokenInfo;
        tokenInfo = SopRequestParse.getAccessTokenInfo(request);
        info.setAccessToken(tokenInfo.getToken());
        info.setRealmId(tokenInfo.getRealmId());
        info.setPlatformId(tokenInfo.getPlatformId());
        return sopUserAuth.updatePassword(info);
    }

    public Boolean register(SopRegisterUserIn authReg) {
        SopAuthPlatform authPlatform = checkPlatform();
        sopUserAuthFeign.register(authPlatform.getModelToken(), authReg);
        return true;
    }

    public SopUserBrief lookupUser(SopUserIdFind idFind) {
        SopAuthPlatform authPlatform = checkPlatform();
        idFind.setRealmId(authPlatform.getRealmId());
        return sopUserAuthFeign.lookupUserBrief(authPlatform.getModelToken(), idFind).getData();
    }
}
